 package com.gmrz.uaf.crypto.internal.handlers;
 
 import com.gmrz.uaf.common.UAFRuntimeException;
 import com.gmrz.uaf.crypto.CryptoConfig;
 import javax.crypto.SecretKey;
 import javax.crypto.spec.SecretKeySpec;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.logging.log4j.LogManager;
 import org.apache.logging.log4j.Logger;

 import java.security.GeneralSecurityException;

 public class ServerDataCipherHandler extends BaseCipherHandler
 {
   private static final Logger LOG = LogManager.getLogger(ServerDataCipherHandler.class);
   private String keyAlgorithm = "AES";
   private SecretKey encryptionSecretKey = null;
 
   public ServerDataCipherHandler(CryptoConfig cryptoConfig) {
     this.transformation = cryptoConfig.getExternalEncryptionTransformation();
     this.keyAlgorithm = cryptoConfig.getExternalEncryptionKeyAlgo();
 
     if (StringUtils.isEmpty(this.transformation)) {
       throwUAFRuntimeException("External encryption transformation cannot be empty.");
     }
 
     if (StringUtils.isEmpty(this.keyAlgorithm)) {
       throwUAFRuntimeException("External encryption key algorithm cannot be empty.");
     }
     initializeSecretKey(cryptoConfig);
   }
 
   private void throwUAFRuntimeException(String errorMessage)
   {
     LOG.error(errorMessage);
     throw new UAFRuntimeException(errorMessage);
   }
 
   private void initializeSecretKey(CryptoConfig cryptoConfig)
   {
       byte[] wrappedKey = cryptoConfig.getExternalEncryptionKey();
       ServerDataKeyParser parser = new ServerDataKeyParser();
       byte[] rawExternalEncryptionKey = null;
       try {
           rawExternalEncryptionKey = parser.decrypt(wrappedKey);
       } catch (GeneralSecurityException e) {
           LOG.error(e);
       }
       // byte[] rawExternalEncryptionKey = cryptoConfig.getExternalEncryptionKey();
 
     if (ArrayUtils.isEmpty(rawExternalEncryptionKey)) {
       throwUAFRuntimeException("External encryption key cannot be empty.");
     }

     if (rawExternalEncryptionKey.length < 16) {
       throw new UAFRuntimeException("External encryption key does not match minimum length criteria.");
     }
 
     this.encryptionSecretKey = new SecretKeySpec(rawExternalEncryptionKey, this.keyAlgorithm);
   }
 
   public SecretKey getKey()
   {
     if (this.encryptionSecretKey == null) {
       throwUAFRuntimeException("External encryption key for ServerData has not been initialized.");
     }
     return this.encryptionSecretKey;
   }
 }
